package com.lx.config;

import com.lx.queue.MessageReceiver;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/**
 * redis配置
 *
 * @author 段誉
 * @create 2019-03-25 9:59
 */
@Configuration
public class RedisConfig {

  /**
   * redis消息监听器容器
   * 可以添加多个监听不同话题的redis监听器，只需要把消息监听器和相应的消息订阅处理器绑定，该消息监听器
   * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
   * @param connectionFactory
   * @param listenerAdapter1
   * @param listenerAdapter2
   * @return
   */
  @Bean
  RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                          MessageListenerAdapter listenerAdapter1,
                                          MessageListenerAdapter listenerAdapter2) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    //订阅了一个叫chat的通道
    container.addMessageListener(listenerAdapter1, new PatternTopic("chat1"));
    //container 可以添加多个 messageListener
    container.addMessageListener(listenerAdapter2, new PatternTopic("chat2"));

    return container;
  }

  /**
   * 消息监听器适配器，绑定消息处理器，利用反射技术调用消息处理器的业务方法
   * @param receiver
   * @return
   */
  @Bean
  MessageListenerAdapter listenerAdapter1(MessageReceiver receiver) {
    //给messageListenerAdapter 传入一个消息接受的处理器，利用反射的方法调用“receiveMessage”
    //不填defaultListenerMethod默认调用handleMessage
    return new MessageListenerAdapter(receiver, "receiverMessage1");
  }
  @Bean
  MessageListenerAdapter listenerAdapter2(MessageReceiver receiver) {
    return new MessageListenerAdapter(receiver, "receiverMessage2");
  }

  /**
   * 读取内容的template
   */
  @Bean
  StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
    return new StringRedisTemplate(connectionFactory);
  }
}
